package main

import (
	"fmt"

	"ddl_checker/internal/parser"
)

func main() {
	fmt.Println("=== 混合SQL分析器演示 ===")
	fmt.Println("优先使用pg_query_go解析，失败后使用TiDB解析")
	fmt.Println()

	// 创建混合分析器
	hybridAnalyzer := parser.NewHybridAnalyzer()

	// 测试用例
	testCases := []struct {
		name string
		sql  string
	}{
		{
			name: "标准的PostgreSQL语法",
			sql:  "CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL);",
		},
		{
			name: "MySQL风格的语法（可能TiDB解析更好）",
			sql:  "CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL) ENGINE=InnoDB;",
		},
		{
			name: "批量SQL语句",
			sql: `CREATE TABLE products (
				id INT PRIMARY KEY,
				name VARCHAR(100),
				price DECIMAL(10,2)
			);

			INSERT INTO products (id, name, price) VALUES (1, 'Laptop', 999.99);

			SELECT * FROM products WHERE price > 500;

			DROP TABLE products;`,
		},
		{
			name: "复杂的JOIN查询",
			sql: `SELECT u.name, o.order_date, SUM(oi.quantity * oi.price) as total
				FROM users u
				JOIN orders o ON u.id = o.user_id
				JOIN order_items oi ON o.id = oi.order_id
				WHERE o.status = 'completed'
				GROUP BY u.id, u.name, o.order_date
				ORDER BY total DESC;`,
		},
	}

	for i, tc := range testCases {
		fmt.Printf("=== 测试用例 %d: %s ===\n", i+1, tc.name)
		fmt.Printf("SQL: %s\n", tc.sql)
		fmt.Println()

		// 使用带回退机制的解析
		statements, usedParser, err := hybridAnalyzer.ParseWithFallback(tc.sql)
		if err != nil {
			fmt.Printf("❌ 解析失败: %v\n", err)
			fmt.Println()
			continue
		}

		fmt.Printf("✅ 解析成功 (使用解析器: %s)\n", usedParser)
		fmt.Printf("解析到 %d 条语句:\n", len(statements))

		for j, stmt := range statements {
			fmt.Printf("  语句 %d:\n", j+1)
			fmt.Printf("    类型: %s\n", stmt.StatementType)
			fmt.Printf("    语法正确: %v\n", stmt.IsValid)
			fmt.Printf("    关联表: %v\n", stmt.Tables)
			fmt.Printf("    关联列: %v\n", stmt.Columns)
			fmt.Printf("    操作: %v\n", stmt.Operations)
			fmt.Printf("    实际使用的解析器: %s\n", stmt.ParserUsed)
			fmt.Printf("    原始SQL: %s\n", stmt.OriginalSQL[:min(100, len(stmt.OriginalSQL))]+"...")
			fmt.Println()
		}

		fmt.Println("========================================")
		fmt.Println()
	}

	// 测试语法验证
	fmt.Println("=== 语法验证测试 ===")
	validationTests := []struct {
		name string
		sql  string
	}{
		{"有效SQL", "SELECT * FROM users;"},
		{"无效SQL", "SELECT * FROM nonexistent_table WHERE syntax_error ="},
		{"PostgreSQL特有语法", "SELECT generate_series(1, 5) as num;"},
		{"MySQL特有语法", "SELECT * FROM users LIMIT 10 OFFSET 20;"},
	}

	for _, test := range validationTests {
		fmt.Printf("测试: %s\n", test.name)
		fmt.Printf("SQL: %s\n", test.sql)

		valid, msg := hybridAnalyzer.ValidateSQL(test.sql)
		if valid {
			fmt.Printf("✅ 语法正确: %s\n", msg)
		} else {
			fmt.Printf("❌ 语法错误: %s\n", msg)
		}
		fmt.Println()
	}

	// 测试语句分割
	fmt.Println("=== 语句分割测试 ===")
	splitSQL := `CREATE TABLE test (id INT); INSERT INTO test VALUES (1); SELECT * FROM test; DROP TABLE test;`

	statements, err := hybridAnalyzer.SplitStatements(splitSQL, ";")
	if err != nil {
		fmt.Printf("❌ 分割失败: %v\n", err)
	} else {
		fmt.Printf("✅ 成功分割为 %d 条语句:\n", len(statements))
		for i, stmt := range statements {
			fmt.Printf("  %d. %s\n", i+1, stmt)
		}
	}
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
